<?php
/**
 * 微信支付信息
 */
namespace app\user\model;
use think\Db;
use think\Exception;

require_once EXTEND_PATH.'wechat/WxPayConfig.php';
require_once EXTEND_PATH.'wechat/WxPay.Data.php';
require_once EXTEND_PATH.'wechat/WxPay.Api.php';
require_once EXTEND_PATH.'wechat/WxPay.Notify.php';
class WeixinPay extends \WxPayNotify
{
    private $setting = [];

    public function __construct($data = [])
    {
        $this->setting = config('app.weixin');
    }

    /**
     * 微信付款到零钱
     * @param $openid
     * @param $money
     */
    public static function withDraw($openid, $money, $order_sn)
    {
        throw new Exception('商户未开通付款到零钱');
        $config = new \WxPayConfig();
        $config->SetKey("548cae6facd00607946b202783afb842");
        $inputObj = new \WxPayWithdraw();
        $inputObj->SetPartnerTradeNo($order_sn);
        $inputObj->SetOpenid($openid);
        $inputObj->SetAmount($money*100);
        $inputObj->SetDesc('书画天下提现');
        $pay_info = \WxPayApi::withdraw($config, $inputObj);
        if($pay_info['return_code'] == 'FAIL'){
            throw new Exception($pay_info['return_msg']);
        }
        if($pay_info['result_code'] == 'FAIL'){
            throw new Exception($pay_info['err_code_des']);
        }
        return $pay_info;

    }

    //下单App
    public function getPrePayOrderApp($body, $out_trade_no, $total_fee)
    {

        $config = new \WxPayConfig();
        $inputObj = new \WxPayUnifiedOrder();
//        out_trade_no、body、total_fee、trade_type
        $inputObj->SetOut_trade_no($out_trade_no);
        $inputObj->SetBody($body);
        $inputObj->SetTotal_fee($total_fee*100);
        $inputObj->SetTrade_type('APP');
        $pay_info = \WxPayApi::unifiedOrder($config, $inputObj);
        if($pay_info['return_code'] == 'FAIL'){
            throw new Exception($pay_info['return_msg']);
        }
        if($pay_info['result_code'] == 'FAIL'){
            throw new Exception($pay_info['err_code_des']);
        }
        $wxsign = new \WxPayDataBaseSignMd5();
        $pay_data = [
            'appid'=>$pay_info['appid'],
            'partnerid'=>$pay_info['mch_id'],
            'prepayid'=>$pay_info['prepay_id'],
            'package'=>'Sign=WXPay',
            'noncestr'=>$pay_info['nonce_str'],
            'timestamp'=>(string)now_datetime()
        ];;
        $wxsign->SetValues($pay_data);
        $sign = $wxsign->MakeSign($config);
        $pay_data['sign'] = $sign;

        return $pay_data;

    }

    //下单H5
    public function getPrePayOrder($body, $out_trade_no, $total_fee)
    {

        $config = new \WxPayConfig();
        $inputObj = new \WxPayUnifiedOrder();
        $inputObj->SetOut_trade_no($out_trade_no);
        $inputObj->SetBody($body);
        $inputObj->SetTotal_fee($total_fee*100);
        $inputObj->SetTrade_type('MWEB');
        $inputObj->SetScene(json_encode([
            'h5_info'=>[
                "type"=>"wap",
                "wap_url"=>'http://www.sdrushanghui.com',
                "wap_name"=>"订单支付"
            ]
        ]));
        $pay_info = \WxPayApi::unifiedOrder($config, $inputObj);
        if($pay_info['return_code'] == 'FAIL'){
            throw new Exception($pay_info['return_msg']);
        }
        if($pay_info['result_code'] == 'FAIL'){
            throw new Exception($pay_info['err_code_des']);
        }
        return $pay_info;

    }
    /**
     * jsapi支付下单
     * @param $body
     * @param $out_trade_no
     * @param $total_fee
     * @param string $notify
     * @param $openid
     * @return array|bool|false|mixed
     */
    public function getPrePayOrder2($body, $out_trade_no, $total_fee,$openid)
    {
        $config = new \WxPayConfig();
        $inputObj = new \WxPayUnifiedOrder();
//        out_trade_no、body、total_fee、trade_type
        $inputObj->SetOut_trade_no($out_trade_no);
        $inputObj->SetBody($body);
        $inputObj->SetTotal_fee($total_fee*100);
        $inputObj->SetTrade_type('JSAPI');
        $inputObj->SetOpenid($openid);
        $pay_info = \WxPayApi::unifiedOrder($config, $inputObj);
        if($pay_info['return_code'] == 'FAIL'){
            throw new Exception($pay_info['return_msg']);
        }
        if($pay_info['result_code'] == 'FAIL'){
            throw new Exception($pay_info['err_code_des']);
        }
        $prepay_id = $pay_info['prepay_id'];
        $config_t = new \WxPayJsApiPay();
        $config_t->SetAppid(config('wechat.appid'));
        $config_t->SetTimeStamp(time());
        $config_t->SetNonceStr(\WxPayApi::getNonceStr());
        $config_t->SetPackage('prepay_id='.$prepay_id);
        $config_t->SetSignType('MD5');
        $config_t->SetSign($config);
        return $config_t->GetValues();
    }

    /**
     * @return bool|\true回调出来完成不需要继续回调，false回调处理未完成需要继续回调|void
     */
    public function NotifyProcess($data, $config, &$msg)
    {
        db()->startTrans();
        try {
            $status = $data->CheckSign($config);
            $arr = $data->GetValues();
            //支付验签
            if($status){
                $order_sn = $arr['out_trade_no'];
                $order_info = db('shop_dingdan')
                    ->where('danhao', $order_sn)
                    ->find();
                if ($order_info['pay_ok'] == 1) {
                    return true;
                }
                //保存支付状态
                $change = [
                    'pay_ok' => 1,
                    'is_ok' => 2,
                    'pay_type' => 'weixin',
                    'pay_sn' => $arr['transaction_id'],
                    'pay_money' => $arr['total_fee'] / 100,
                    'pay_time' => time()
                ];
                db('shop_dingdan')->where('id', $order_info['id'])->update($change);
                //减少库存
                db('shop')->where('id='.$order_info['shop_id'])->setDec('kucun',$order_info['num']);
                //删除购物车

                db('shop_car')->where('shop_id', $order_info['shop_id'])->where('userid', $order_info['userid'])->delete();
                $cp=db('shop')->where('id', $order_info['shop_id'])->find();
                if($cp['catid']==6){
                    $pv=$cp['pv'];
                    jihuo($order_info['userid'],$pv);
                    daili($order_info['userid'],$order_info['shop_id']);
                }

            }else{
                echo "签名验证失败";
            }
            db()->commit();
        }catch (\Exception $e){
            db()->rollback();
        }
        return true;
    }



    /**
     * 查询订单状态  暂不使用
     * @param $transaction_id
     * @return string
     */
    public function getPayStatus($transaction_id)
    {
        $config = new \WxPayConfig();
        $inputObj = new \WxPayOrderQuery();
        $inputObj->SetTransaction_id($transaction_id);
        $status = \WxPayApi::orderQuery($config, $inputObj);
    }
}